package com.util;

import java.io.UnsupportedEncodingException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.sql.Connection;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;

/**
 *
 * <p>Title: StringUtils</p>
 *
 * <p>Description: String Utilities</p>
 *
 * <p>Copyright: Copyright (c) 2005</p>
 *
 * <p>Company: </p>
 *
 * @author ShiYongxin
 * @version 1.0
 */
public abstract class StringUtils {
	/**
	 * add by zhuyoulong
	 */
	public static boolean systemEncodingIsUTF8 = "UTF-8".equals(System.getProperty("file.encoding"));
	
    private static final Log logger = LogFactory.getLog(StringUtils.class);


    /**
     * Check if an Object is empty
     * @param obj Object
     * @return boolean
     */
    public static boolean isEmpty(Object obj) {
        if (obj == null)
            return true;
        else if (obj instanceof String)
            return ( (String) obj).length() == 0;
        else
            return false;
    }

    /**
     * Check if a String is empty
     * @param aString String
     * @return boolean
     */
    public static boolean isEmpty(String aString) {
        return !hasLength(aString);
    }
    
    /**
     * Check if a String is empty
     * @param aString String
     * @return boolean
     */
    public static boolean isInteger(String aString) {
        try
        {
        	new Integer(aString).intValue();
        	return true;
        }
        catch(Exception exp)
        {
        	return false;
        }
    }

    /**
     * Check if a String has length.
     * <p><pre>
     * StringUtils.hasLength(null) = false
     * StringUtils.hasLength("") = false
     * StringUtils.hasLength(" ") = true
     * StringUtils.hasLength("Hello") = true
     * </pre>
     * @param str the String to check, may be null
     * @return <code>true</code> if the String is not null and has length
     */
    public static boolean hasLength(String str) {
        return (str != null && str.length() > 0);
    }

    /**
     * Check if a String has text. More specifically, returns <code>true</code>
     * if the string not <code>null<code>, it's <code>length is > 0</code>, and
     * it has at least one non-whitespace character.
     * <p><pre>
     * StringUtils.hasText(null) = false
     * StringUtils.hasText("") = false
     * StringUtils.hasText(" ") = false
     * StringUtils.hasText("12345") = true
     * StringUtils.hasText(" 12345 ") = true
     * </pre>
     * @param str the String to check, may be null
     * @return <code>true</code> if the String is not null, length > 0,
     *         and not whitespace only
     * @see java.lang.Character#isWhitespace
     */
    public static boolean hasText(String str) {
        int strLen;
        if (str == null || (strLen = str.length()) == 0) {
            return false;
        }
        for (int i = 0; i < strLen; i++) {
            if (!Character.isWhitespace(str.charAt(i))) {
                return true;
            }
        }
        return false;
    }

    /**
     * Trim leading whitespace from the given String.
     * @param str the String to check
     * @return the trimmed String
     * @see java.lang.Character#isWhitespace
     */
    public static String trimLeadingWhitespace(String str) {
        if (str.length() == 0) {
            return str;
        }
        StringBuffer buf = new StringBuffer(str);
        while (buf.length() > 0 && Character.isWhitespace(buf.charAt(0))) {
            buf.deleteCharAt(0);
        }
        return buf.toString();
    }

    /**
     * Trim trailing whitespace from the given String.
     * @param str the String to check
     * @return the trimmed String
     * @see java.lang.Character#isWhitespace
     */
    public static String trimTrailingWhitespace(String str) {
        if (str.length() == 0) {
            return str;
        }
        StringBuffer buf = new StringBuffer(str);
        while (buf.length() > 0 && Character.isWhitespace(buf.charAt(buf.length() - 1))) {
            buf.deleteCharAt(buf.length() - 1);
        }
        return buf.toString();
    }


    /**
     * Test if the given String starts with the specified prefix,
     * ignoring upper/lower case.
     * @param str the String to check
     * @param prefix the prefix to look for
     * @return boolean
     * @see java.lang.String#startsWith
     */
    public static boolean startsWithIgnoreCase(String str, String prefix) {
        if (str == null || prefix == null) {
            return false;
        }
        if (str.startsWith(prefix)) {
            return true;
        }
        if (str.length() < prefix.length()) {
            return false;
        }
        String lcStr = str.substring(0, prefix.length()).toLowerCase();
        String lcPrefix = prefix.toLowerCase();
        return lcStr.equals(lcPrefix);
    }

    /**
     * from ISO-8859-1 to GBK
     * @param input String
     * @return String
     */
    public static String ISO2GBK(String input) {
        if (input == null) {
            return null;
        }

        try {
            return new String(input.getBytes("ISO-8859-1"), "GBK");
        }
        catch (UnsupportedEncodingException ex) {
            logger.error("Unsupported encoding", ex);
            return null;
        }
    }

    /**
     * from GBK ot ISO-8859-1
     * @param input String
     * @return String
     */
    public static String GBK2ISO(String input) {
        if (input == null) {
            return "";
        }

        try {
            return new String(input.getBytes("GBK"), "ISO-8859-1");
        }
        catch (UnsupportedEncodingException ex) {
            logger.error("Unsupported encoding", ex);
            return null;
        }
    }
    /**
     * from ISO-8859-1 to utf8
     * @param input String
     * @return String
     */
    public static String ISO2UTF(String input) {
        if (input == null) {
            return "";
        }

        try {
            return new String(input.getBytes("ISO-8859-1"), "UTF-8");
        }
        catch (UnsupportedEncodingException ex) {
            logger.error("Unsupported encoding", ex);
            return null;
        }
    }
    /**
     * get method name according to property name
     * @param prefix String
     * @param propertyName String
     * @return String
     */
    public static String getMethodName(String prefix, String propertyName){
        if (!hasText(propertyName)){
            return null;
        }
        else{
            return prefix + propertyName.substring(0, 1).toUpperCase() + propertyName.substring(1);
        }
    }
	public static String getMyDate(String strdate){
		String ret = "";
		if(strdate!=null && !strdate.equals("") && strdate.length()>0 && !strdate.startsWith("1900-01-01"))
			ret = strdate.substring(0,10);
		return ret;
	}

	//for example:yy-mm-dd hh:mi
	public static String getMyDate2(String strdate){
		String ret = "";
		if(strdate!=null && !strdate.equals("") && strdate.length()>0 && !strdate.startsWith("1900-01-01"))
			ret = strdate.substring(0,16);
		return ret;
	}
    /**
     * getMoneyFormat
     *
     * @param amount Object
     * @return String
     */
    public static String getMoneyFormat(Object amount){
        NumberFormat usFormat = NumberFormat.getCurrencyInstance(Locale.US);
        if (Double.parseDouble(amount.toString())<0){
            String formatTemp=usFormat.format(amount);
            return "-"+formatTemp.substring(2,formatTemp.length()-1);
        }
        return usFormat.format(amount).substring(1);
    }
    
    
    /**
	 * ��list���object把list里的object转成string
	 * @param objarrayList
	 * @return
	 */
	public static List<String[]> getStringArrListFromObjectArrList(List objarrayList) {
		Object[] objarr = null;
		List<String[]> sub = new ArrayList<String[]>();
		for (Iterator it = objarrayList.iterator(); it.hasNext();) {
			objarr = (Object[]) it.next();
			if(objarr != null){
				sub.add(getStringArrayFromObjectArray(objarr));
			}
			
		}
		// sub.add(total);
		return sub;
	}
	/**
	 * ��object��ת��string
	 * @param objarr
	 * @return
	 */
	public static String[] getStringArrayFromObjectArray(Object[] objarr) {
		String[] rs = new String[objarr.length];

		for (int i = 0; i < objarr.length; i++) {
			if (objarr[i] != null) {
				rs[i] = objarr[i].toString();
			} else {
				rs[i] = "";
			}
		}
		return rs;
	}
	
	/**
     * 自动裁剪汉字。主要是用于系统是ISO-8859-1编码方式，需要剪一段字符串前面部分。
     * 由于一个汉字占两个位置。所以，剪的时候有时会把汉字分开。目前这种方式不会，<br>
     * --------------------------------------------------------------------------<br>
     * 创建者：朱有龙<br>
     * 创建日期：2008-1-9<br>
     * <br>
     * 修改者：<br>
     * 修改日期：<br>
     * 修改原因：<br>
     * --------------------------------------------------------------------------<br>
     *
     * @param hz 要剪切的字符串
     * @param n  剪多长
     * @return 剪切后的结果
     */
    public static String autoCutHZ(String hz,
                                   int n) {
        if (hz == null || hz.length() == 0)
            return "";
        else
            return hz.length() <= n ? hz : cutHZ(hz,
                    n) + "...";
    }

    /**
     * 自动裁剪汉字。主要是用于系统是ISO-8859-1编码方式，需要剪一段字符串前面部分。
     * 由于一个汉字占两个位置。所以，剪的时候有时会把汉字分开。目前这种方式不会，<br>
     * --------------------------------------------------------------------------<br>
     * @author:zhuyoulong
     * <br>
     * 修改者：<br>
     * 修改日期：<br>
     * 修改原因：<br>
     * --------------------------------------------------------------------------<br>
     *
     * @param hz 要剪切的字符串
     * @param n  剪多长
     * @return 剪切后的结果
     */
    public static String cutHZ(String hz,
                               int n) {
        if (hz == null)
            return null;
        boolean flag = true;
        String hzCut = "";
        if (hz.length() < n)
            n = hz.length();
        if (n == 0)
            return "";
        if (n == 1)
            if (hz.charAt(1) >= '\177')
                return " ";
            else
                return hz.charAt(1) + "";
        for (int i = 0; i < n; i++)
            if (i == n - 1) {
                if (hz.charAt(i) >= '\177') {
                    if (!flag)
                        hzCut = hzCut + hz.charAt(i - 1) + hz.charAt(i);
                } else if (!flag)
                    hzCut = hzCut + "_" + hz.charAt(i);
                else
                    hzCut = hzCut + hz.charAt(i);
            } else if (flag) {
                if (hz.charAt(i) >= '\177')
                    flag = false;
                else
                    hzCut = hzCut + hz.charAt(i);
            } else {
                if (hz.charAt(i) < '\177')
                    hzCut = hzCut + '_' + hz.charAt(i);
                else
                    hzCut = hzCut + hz.charAt(i - 1) + hz.charAt(i);
                flag = true;
            }

        return hzCut;
    }
    
    /**
     * 
     * <p>功能描述：字符串替换</p>
      * @param str    原文字符串
     * @param oldstr 要替换的字符串
     * @param newstr 替换成新的字符串
     * @return 替换后的结果
     * @throws Exception
     * @author:zhuyoulong
     * @update:[日期YYYY-MM-DD][更改人姓名][变更描述]
     */
    public static String replace(String str,
                                 String oldstr,
                                 String newstr)
            throws Exception {
        if (str == null)
            return null;
        if (oldstr == null || oldstr.equals("") || newstr == null)
            return str;
        int olen = oldstr.length();
        int iat = 0;
        StringBuilder bstr = new StringBuilder();
        do {
            iat = str.indexOf(oldstr);
            if (iat < 0) {
                bstr.append(str);
                break;
            }
            bstr.append(str.substring(0,
                    iat));
            bstr.append(newstr);
            str = str.substring(iat + olen,
                    str.length());
        } while (true);
        String s = bstr.toString();
        bstr = null;
        return s;
    }
}
